//
//  DR_FileManager.swift
//  DocReaderRP
//
//  Created by  mac on 2025/11/14.
//

import UIKit
import PDFKit

class DR_FileManager {
    
    static let shared = DR_FileManager()
    
    private init() {}
    
    // MARK: - 获取所有文件（PDF、Word、Excel、PPT）
    /// 获取所有类型的文件列表
    /// - Returns: 文件模型数组，按创建时间倒序排列
    func getAllFiles() -> [DR_FileModel] {
        let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
        
        var allFiles: [DR_FileModel] = []
        
        // 支持的文件夹
        let folders = ["PDFs", "Word", "Excel", "PPT"]
        
        for folder in folders {
            let folderPath = documentsPath.appendingPathComponent(folder, isDirectory: true)
            
            guard let fileURLs = try? FileManager.default.contentsOfDirectory(
                at: folderPath,
                includingPropertiesForKeys: [.fileSizeKey, .creationDateKey],
                options: [.skipsHiddenFiles]
            ) else {
                continue
            }
            
            let files = fileURLs.compactMap { url -> DR_FileModel? in
                // 验证文件类型
                let fileExtension = url.pathExtension.lowercased()
                guard DR_FileType.from(fileExtension: fileExtension) != nil else {
                    return nil
                }
                
                return DR_FileModel(fileURL: url)
            }
            
            allFiles.append(contentsOf: files)
        }
        
        // 按创建时间倒序排列
        return allFiles.sorted { $0.createDate > $1.createDate }
    }
    
    // MARK: - 获取 PDF 文件列表
    func getPDFFiles() -> [DR_FileModel] {
        return getAllFiles().filter { $0.fileType == .pdf }
    }
    
    // MARK: - 获取 Word 文件列表
    func getWordFiles() -> [DR_FileModel] {
        return getAllFiles().filter { $0.fileType == .word }
    }
    
    // MARK: - 获取 Excel 文件列表
    func getExcelFiles() -> [DR_FileModel] {
        return getAllFiles().filter { $0.fileType == .excel }
    }
    
    // MARK: - 获取 PPT 文件列表
    func getPPTFiles() -> [DR_FileModel] {
        return getAllFiles().filter { $0.fileType == .ppt }
    }
    
    // MARK: - 获取文件预览图
    func getFileThumbnail(fileURL: URL, fileType: DR_FileType, size: CGSize = CGSize(width: 200, height: 240)) -> UIImage? {
        switch fileType {
        case .pdf:
            return DR_PDFTool.shared.getPDFThumbnail(fileURL: fileURL, size: size)
        case .word, .excel, .ppt:
            // 其他文件类型返回默认图标
            return UIImage(named: fileType.iconName)
        }
    }
    
    // MARK: - 收藏管理
    /// 获取文件的唯一标识符（用于收藏存储）
    private func getFileIdentifier(for fileModel: DR_FileModel) -> String {
        // 使用文件名+文件大小+创建日期作为唯一标识
        let timestamp = String(format: "%.0f", fileModel.createDate.timeIntervalSince1970)
        return "\(fileModel.fileName)_\(fileModel.fileSize)_\(timestamp)"
    }
    
    /// 检查文件是否已收藏
    func isFavorite(_ fileModel: DR_FileModel) -> Bool {
        let identifier = getFileIdentifier(for: fileModel)
        let favorites = getFavoriteIdentifiers()
        return favorites.contains(identifier)
    }
    
    /// 添加收藏
    func addFavorite(_ fileModel: DR_FileModel) {
        let identifier = getFileIdentifier(for: fileModel)
        var favorites = getFavoriteIdentifiers()
        favorites.insert(identifier)
        saveFavoriteIdentifiers(favorites)
    }
    
    /// 移除收藏
    func removeFavorite(_ fileModel: DR_FileModel) {
        let identifier = getFileIdentifier(for: fileModel)
        var favorites = getFavoriteIdentifiers()
        favorites.remove(identifier)
        saveFavoriteIdentifiers(favorites)
    }
    
    /// 切换收藏状态
    func toggleFavorite(_ fileModel: DR_FileModel) -> Bool {
        if isFavorite(fileModel) {
            removeFavorite(fileModel)
            return false
        } else {
            addFavorite(fileModel)
            return true
        }
    }
    
    /// 获取所有收藏的文件标识符
    private func getFavoriteIdentifiers() -> Set<String> {
        if let array = UserDefaults.standard.array(forKey: "FAVORITE_FILES") as? [String] {
            return Set(array)
        }
        return Set<String>()
    }
    
    /// 保存收藏的文件标识符
    private func saveFavoriteIdentifiers(_ favorites: Set<String>) {
        UserDefaults.standard.set(Array(favorites), forKey: "FAVORITE_FILES")
        UserDefaults.standard.synchronize()
    }
    
    /// 获取所有收藏的文件
    func getFavoriteFiles() -> [DR_FileModel] {
        let allFiles = getAllFiles()
        return allFiles.filter { isFavorite($0) }
    }
}

